package ch13.streams;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class CreatingStreams {
    public static void main(String[] args) throws IOException {
        var path = Path.of("ch09/set/alice30.txt");
        var contents = Files.readString(path);

        var words = Stream.of(contents.split("\\PL+"));
        show("words", words);

        var song  = Stream.of("gently", "down", "the", "stream");
        show("song", song);

        // 空流
        Stream<String> silence = Stream.empty();
        show("silence", silence);

        // 无限流
        var echos = Stream.generate(() -> "Echo");
        show("echos", echos);

        var randoms = Stream.generate(Math::random);
        show("randoms", randoms);

        // 无限流
        var integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
        show("integers", integers);

        var greetings = "Hello\nGuten Tag\nBonjour".lines();
        show("greetings", greetings);

        var wordsAnotherWay = Pattern.compile("\\PL+").splitAsStream(contents);
        show("wordsAnotherWay", wordsAnotherWay);

        try (var lines = Files.lines(path)) {
            show("lines", lines);
        }

        var it = FileSystems.getDefault().getRootDirectories();
        var rootDirs = StreamSupport.stream(it.spliterator(), false);
        show("rootDirs", rootDirs);


        var iterator = Path.of("ch02", "ch03", "ch01").iterator();

        // 将迭代器转换未一个未知尺寸可分割的迭代器
        var spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED);

        var paths = StreamSupport.stream(spliterator, false);
        show("paths", paths);
    }

    public static <T> void show(String title, Stream<T> stream) {
        final int SIZE = 10;

        var firstElements = stream.limit(SIZE + 1).toArray();

        System.out.print(title + ": ");
        for (int i = 0; i < firstElements.length; i++) {
            if (i > 0) {
                System.out.print(", ");
            }
            if (i < SIZE) {
                System.out.print(firstElements[i]);
            }
            else {
                System.out.print("...");
            }
        }

        System.out.println();
    }
}
